const Router = require('koa-router');
const router = new Router();
const moment = require('moment');
const siteinfo = require('./siteinfo.json');

function setAllowOriginHeader(ctx) {
  const origin = ctx.request.header.origin || '*';
  ctx.set('Access-Control-Allow-Origin', origin);
}

function setOptionsCorsHeaders(ctx) {
  setAllowOriginHeader(ctx);
  ctx.set('Access-Control-Allow-Headers', 'Content-Type');
  ctx.set('Access-Control-Allow-Methods', 'POST, OPTIONS');
}

router.get('/', async function (ctx) {
  ctx.state.session = this.session;
  ctx.state.timestamp = moment().format('YYYY-MM-DD HH:mm:ss');
  ctx.cookies.set('name', 'feng', { signed: true });
  await ctx.render('pages/index.hbs', siteinfo);
});

router.get('/cors/get', async function (ctx) {
  setAllowOriginHeader(ctx);
  ctx.set('Cache-Control', 'no-cache');
  ctx.body = {
    code: 0,
    msg: 'ok'
  };
});

router.post('/cors/post', async function (ctx) {
  setAllowOriginHeader(ctx);
  ctx.set('Cache-Control', 'no-cache');
  ctx.body = {
    code: 0,
    msg: 'good'
  };
});

router.options('/cors/post', async function (ctx) {
  setOptionsCorsHeaders(ctx);
  ctx.set('Cache-Control', 'no-cache');
  ctx.status = 200;
});

module.exports = router;
